/********************************************************************************
  * @file    main.cpp
  * @author  Lun Li
  * @version V1.1.0
  * @date    2021.11.9
  * @brief   This file contains a main function.
  *******************************************************************************/

#include "mainwindow.h"

#include <QApplication>
#include <QMutex>
#include <QTranslator>
#define DEBUG_FILE_MAXSIZE 1024*1024*100

// 将程序运行时产生的崩溃错误信息或debug信息输出到日志文件中
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();
    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        break;
    case QtWarningMsg:
        text = QString("Warning:");
        break;
    case QtCriticalMsg:
        text = QString("Critical:");
        break;
    case QtFatalMsg:
        text = QString("Fatal:");
        break;
    default:
        break;
    }
    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)").arg(current_date_time);
    QString message = QString("%1 %2 %3 %4").arg(text, context_info, msg, current_date);
    QFile file("log.txt");
    if (file.size() > DEBUG_FILE_MAXSIZE)
    {
        file.open(QIODevice::ReadOnly);
        QByteArray content = file.readAll();
        file.close();
        file.open(QIODevice::WriteOnly);
        QTextStream clear_stream(&file);
        clear_stream << content.right(int(content.length() / 2));
        file.flush();
        file.close();
    }
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message;
    file.flush();
    file.close();
    mutex.unlock();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

// 若为0，则会在Qt Creator调试时输出debug信息，否则调试信息会输出到log.txt文件中。
#if 1
    qInstallMessageHandler(outputMessage);
#endif

    // 创建程序的配置文件
    ProgramConfig *configFile = new ProgramConfig("config.ini", QSettings::IniFormat);

    // 检测配置里的语言
    if (configFile->languageIndex() == 0) {
        QTranslator *translator = new QTranslator();
        translator->load("EDA_zh_CN.qm"); // 载入中文语言文件
        QCoreApplication::installTranslator(translator);
    }

    MainWindow w(configFile);
    w.showMaximized();
    return a.exec();
}


